package com.study.spring.netty.time_server;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.study.spring.netty.TimeBean;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author zhang
 * @version 1.0
 * @date 2019/5/7 0007
 * @since jdk1.8
 */
public class TimeServerHandler extends ChannelInboundHandlerAdapter {

    private final AtomicLong xl = new AtomicLong(0);
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("{} 加入聊天室", ctx.channel().remoteAddress().toString());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("{}连接中断", ctx.channel().remoteAddress().toString(), cause);
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg.toString().contains("error")) {
            ctx.writeAndFlush(msg);
            ctx.close();
            return;
        }

        if (msg.toString().contains("sof")) {
            ctx.writeAndFlush(msg);
            return;
        }
        logger.info("[ {} ] 请求消息: {}", ctx.channel().remoteAddress(), msg);
        String date = DateUtil.format(new Date(), DatePattern.NORM_DATETIME_FORMAT);
        String[] timeBeans = date.split(" ");
        TimeBean timeBean = new TimeBean(timeBeans[0], timeBeans[1]);
        ctx.writeAndFlush(timeBean);
        xl.addAndGet(1L);
        logger.info("处理第{}次请求", xl.get());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.warn(ctx.channel().remoteAddress() + " exit!");
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) {
                logger.info("无接收消息关闭channel=={}", ctx.channel().remoteAddress());
                ctx.writeAndFlush("finally soft........................................................................");
                ctx.close();
            }
        }
        super.userEventTriggered(ctx, evt);
    }
}
